package dgut.haitaobao.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import dgut.haitaobao.util.response.HttpResponse;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//拦截token进行校验
@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    private void doResultVo(HttpServletResponse servletResponse,HttpResponse httpResponse) throws IOException {
        //响应请求
        servletResponse.setContentType("application/json");
        servletResponse.setCharacterEncoding("utf-8");
        PrintWriter writer=servletResponse.getWriter();
        String resultVo = new ObjectMapper().writeValueAsString(httpResponse);
        writer.write(resultVo);
        writer.flush();
        writer.close();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //预见请求头传餐的首次传参方式为 "OPTION",所以应该对首次请求方式做出反应-放行"option"请求
        String method = request.getMethod();
        if ("OPTIONS".equalsIgnoreCase(method)){
//            String token = request.getHeader("token");
            String token = request.getParameter("token");
            if (token==null){
                //响应请求
                HttpResponse<Object> httpResponse = HttpResponse.error("请先登录");
                doResultVo(response,httpResponse);
                return false;
            }else {
                //验证token,使用jwt来校验
                JwtParser parser= Jwts.parser();
                parser.setSigningKey("haitaobao");
                try {
                    Jws<Claims> claimsJws = parser.parseClaimsJws(token);//如果token正确（密码正确，有效期内)则正常执行,否则抛出异常
                    //Claims body = claimsJws.getBody();//获取token的用户数据
                    //String subject = body.getSubject(); //获取生成token设置的subject
                    //String v1 = body.get("key1", String.class); //获取生成token时存储的Claims的map中的值
                    HttpResponse<Object> httpResponse = HttpResponse.success("登录成功");
                    doResultVo(response,httpResponse);
                    return true;
                }catch (ExpiredJwtException e){
                    HttpResponse<Object> httpResponse = HttpResponse.error("登录过期，请重新登录");
                    doResultVo(response,httpResponse);
                    return false;
                }catch (UnsupportedJwtException e){
                    HttpResponse<Object> httpResponse = HttpResponse.error("token非法");
                    doResultVo(response,httpResponse);
                    return false;
                }catch (Exception e){
                    HttpResponse<Object> httpResponse = HttpResponse.error("请先登录");
                    doResultVo(response,httpResponse);
                    return false;
                }
            }
        }
        return false;

    }
}
